import React, { useEffect, useState } from "react";
import Switch from "react-switch";
import { SidebarStudent } from "../../../components/Sidebar";
import { GetGradingTasks, GetGrades, GetQuestions } from "../../../api";
import { Modal } from "antd";
import "./index.less";
import { GradingTask, Grade, Question } from "../../../utils/constant";
import { useParams } from "react-router-dom";

const columns = [
  {
    title: "PairingId",
    dataIndex: "pairId",
    key: "pairId",
  },
  {
    title: "SubmissionId",
    dataIndex: "submissionId",
    key: "submissionId",
  },
  {
    title: "AssignmentId",
    dataIndex: "assignmentId",
    key: "assignmentId",
  },
  {
    title: "Active",
    dataIndex: "active",
    key: "active",
  },
  {
    title: "FileKey",
    dataIndex: "fileKey",
    key: "fileKey",
  },
  {
    title: "QuestionId",
    dataIndex: "questionId",
    key: "questionId",
  },
  {
    title: "Content",
    dataIndex: "content",
    key: "content",
    ellipsis: true,
  },
];

const Index: React.FC = () => {
  const [tasks, setTasks] = useState<GradingTask[]>([]);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [grades, setGrades] = useState<Grade[]>([]);
  const [isGradeModalOpen, setIsGradeModalOpen] = useState<boolean>(false);
  const [isCommentModalOpen, setIsCommentModalOpen] = useState<boolean>(false);
  const params = useParams();
  const assignmentId = +params.assignmentId!;

  const fetchGradingTasks = async () => {
    try {
      const { data } = await GetGradingTasks();
      setTasks(data);
    } catch (e) {
      console.error(e);
    }
  };

  const fetchQuestionList = async () => {
    try {
      const res = await GetQuestions({ assignmentId });
      const { code, msg } = res;
      if (code !== "00000") {
        throw new Error(msg);
      }
      setQuestions(res.data);
    } catch (e: any) {
      console.error(e);
    }
  };

  const fetchGrades = async (pairId: number) => {
    try {
      const { data } = await GetGrades(pairId);
      const res = data['data'];
      res.sort(function(a: Grade, b: Grade){
        // sort according to rubricId in ascending (question) order
        return a.rubricId - b.rubricId;
      });
      setGrades(res);
    } catch (e) {
      console.error(e);
    }
  }

  const openGradeModal = () => {
    setIsGradeModalOpen(true);
  };
  const closeGradeModal = () => {
    setIsGradeModalOpen(false);
  };
  const openCommentModal = () => {
    setIsCommentModalOpen(true);
  };
  const closeCommentModal = () => {
    setIsCommentModalOpen(false);
  };

  const handleCompleted = () => { return; };

  useEffect(() => {
    fetchGradingTasks();
    fetchQuestionList();
  }, []);

  return (
    <>
      <SidebarStudent></SidebarStudent>
      <div className="grading">
        <h4>Tasks assigned to you for grading and reviewing:</h4>
        <table id="task-table" >
          <thead>
            <tr>
              <th>Pairing ID</th>
              <th>Review</th>
              <th>Grade</th>
              <th>Comment</th>
              <th>Completed?</th>
            </tr>
          </thead>
          <tbody>
            {tasks.map((val, key) => {
              return (val.assignmentId === assignmentId ? (
                <tr key={key}>
                  <td>{val.pairId}</td>
                  <td>
                    <a href= {
                      "../../../pdfAnnotator.html?pdf_url=" +
                      "http://localhost:8080/grade/getSubmissionFile/" +
                      val.fileKey +
                      "&assignmentId=" +
                      val.assignmentId +
                      "&pairingId=" +
                      val.pairId +
                      "&submissionId=" +
                      val.submissionId}
                    >
                      <button id="review-task-button">Start Review</button>
                    </a>
                  </td>
                  <td>
                    <button
                      id="grade-task-button"
                      onClick={() => {
                        fetchGrades(val.pairId);
                        openGradeModal();
                      }}>View Grades
                    </button>
                  </td>
                  <td>
                    <button
                      id="comment-task-button"
                      onClick={() => {
                        fetchGrades(val.pairId);
                        openCommentModal();
                      }}>View Comments
                    </button>
                  </td>
                  {
                  val.active === 3 ? ( // Pending Challenge
                    <td>Pending challenge</td>
                  ) :
                  val.active === 2 ? ( // VOIDED
                    <td style={{color: "red"}}>VOIDED</td>
                  ) :
                  val.active === 1 ? ( // completed
                    <td>
                      <img src="/images/greentick.png" width="20"></img>
                    </td>
                  ) :
                  val.active === 0 ? ( // not completed
                    <td>
                      <img src="/images/greycross.png" width="20"></img>
                    </td>
                  ) : (<td></td>)
                  }
                </tr>
                ) : (<tr></tr>)
              );
            })}
          </tbody>
        </table>
        <Modal
          title="View Grades"
          open={isGradeModalOpen}
          onOk={closeGradeModal}
          onCancel={closeGradeModal}
        >
          {grades.map((val, key) => {
            return (
              <div key={key}>
                <p>Q{key+1}: <b>{val.grade}</b> / {questions.at(key)?.maxMark}</p>
              </div>
            )
          })}
        </Modal>
        <Modal
          title="View Comments"
          open={isCommentModalOpen}
          onOk={closeCommentModal}
          onCancel={closeCommentModal}
        >
          {grades.map((val, key) => {
            return (
              <div key={key}>
                <p>Q{key+1}: {val.comment}</p>
              </div>
            )
          })}
        </Modal>
      </div>
    </>
  );
};

export default Index;
